//
//  MyZTCarDetailTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/27.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "NoramlCellMode.h"
#import "HeaderModel.h"
#import "PeizhiMode.h"
#import "PhotoTitleMode.h"
#import "NormalTitleMode.h"
#import "MyZTCarDetailTableViewController.h"
#import "NameMode.h"
#import "BlueDetailMode.h"
#import "HeaderTableViewCell.h"
#import "NoramlTableViewCell.h"
#import "PhotoTitleTableViewCell.h"
#import "NormallTitleTableViewCell.h"
#import "PeiZhiTableViewCell.h"
#import "FooterView.h"
#import "ShareView.h"
#import "ZTPhotoMode.h"
#import "ZTPhotoTableViewCell.h"
#import "ZtEidtBar.h"
#import "addTableViewController.h"
#import "Puser.h"
#import "ZCDetailMode.h"
#import "UserInfoUpdateResde.h"
#import "ZTFooterView.h"
#import "UMSocial.h"
#import "ShareWithBackView.h"
#import "MyZTTableViewController.h"
@interface MyZTCarDetailTableViewController ()
<UITableViewDataSource,UITableViewDelegate,ShareclickDelegate,EidtBarDelegate,ShareWithBackToIndexDelegate>{
    BOOL _isedting;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataarray;
@property (nonatomic,strong) FooterView *footer;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) ZCDetailMode *mode;
@end

@implementation MyZTCarDetailTableViewController
+(instancetype)Viewcontroller{
    MyZTCarDetailTableViewController *myallvc=[[self alloc]init];
    myallvc.hidesBottomBarWhenPushed=YES;
    return myallvc;
}

-(void)buttonclick:(NSInteger)ButtonIndex{
    if (ButtonIndex==0) {
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[MyZTTableViewController class]]) {
                [self.navigationController popToViewController:vc animated:YES];
                return;
            }
        }
        MyZTTableViewController *vc=[MyZTTableViewController viewcontroller];
        vc.isFromALL=YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self share];
    }
}

-(void)shareclickWithIndex:(NSInteger)index{
    NSString *imgurl;
    if (self.mode.pic.count>0) {
        imgurl=self.mode.pic[0];
    }else{
        imgurl=self.brand_logo;
    }
    
    UMSocialUrlResource *resource=[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:[NSString getImageURLstr:imgurl]];
    [UMSocialData defaultData].extConfig.wxMessageType =UMSocialWXMessageTypeWeb;
    NSString *gourl=[NSString stringWithFormat:@"%@%@%@",websitehosturl,@"/modules.php?app=car_display_info&id=",self.mode.ID];;
  
    NSString *subtitle=[NSString stringWithFormat:@"总报价:%@元|省:%@元,新车报价来自%@",self.mode.allprice,self.mode.yhprice, self.mode.title];
    
    switch (index) {
        case 0:
        {
            
            [UMSocialData defaultData].extConfig.wechatSessionData.url = gourl;
            
            
            
            [UMSocialData defaultData].extConfig.wechatSessionData.title =[NSString stringWithFormat:@"%@",self.mode.cat_name];
            
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:subtitle image:nil location:nil urlResource:resource presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    NSLog(@"分享成功！");
                }
            }];
        }
            break;
        case 1:
        {
            [UMSocialData defaultData].extConfig.wechatTimelineData.url = gourl;
            
            [UMSocialData defaultData].extConfig.wechatTimelineData.title =[NSString stringWithFormat:@"%@",self.mode.cat_name];
            
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:subtitle image:nil location:nil urlResource:resource presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    NSLog(@"分享成功！");
                }
            }];
        }
            break;
            
        case 2:
        {
            
            
            
        }
            break;
            
        default:
            break;
    }
    

}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 56, 0);
    self.navigationItem.title=@"展车详情";    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    ShareWithBackView *shareview=[ShareWithBackView sharewithback];
    shareview.delegate=self;
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:shareview];
    
    
   
   
    if (!self.isFromSearch) {
        [self setuptoolbar];
    }
    if (self.isFromSUS) {
        NSMutableArray *vcarray=[[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
        [vcarray removeObjectAtIndex:self.navigationController.viewControllers.count-2];
        [vcarray removeObjectAtIndex:self.navigationController.viewControllers.count-3];
        self.navigationController.viewControllers = vcarray;
    }

}

-(void)setID:(NSString *)ID{
    _ID=ID;
    [self getdataFromWeb];
}

-(void)getdataFromWeb{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"show_display";
    NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"type"]=@"person";
        params[@"user_id"]=self.user.user_id;
    }else{
        params[@"type"]=@"company";
        params[@"user_id"]=self.user.com_id;
        if (power==8) {
            params[@"pid"]=self.user.parent_id;
        }
    }
    params[@"id"]=self.ID;
    
    [PostUitls Post:myzturl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            
            
            NSDictionary *data=dict[@"data"];
            
            [ZCDetailMode setupReplacedKeyFromPropertyName:^NSDictionary *{
                return @{
                         @"ID" : @"id"
                         };
            }];
            
            ZCDetailMode *mode=[ZCDetailMode objectWithKeyValues:data];
            self.mode=mode;
            [self setupdata];
        }
        
    } failure:^(NSError *error) {
        
    }];

    

}
-(void)EidtClickWithIndex:(NSInteger)index{
    if (index==1) {
        addTableViewController *addvc=[addTableViewController Viewcontroller];
        addvc.mode=self.mode;
        [self.navigationController pushViewController:addvc animated:YES];
    }else{
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"正在操作";
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"action"]=@"del_display";
        NSInteger power=[self.user.power integerValue];
        if (power<5) {
            params[@"type"]=@"person";
            params[@"user_id"]=self.user.user_id;
        }else{
            params[@"type"]=@"company";
            params[@"user_id"]=self.user.com_id;
        }
        
        NSMutableArray *IDarray=[NSMutableArray array];
        [IDarray addObject:self.mode.ID];
        params[@"dis_id"]=[NSString DataTOjsonString:IDarray];
        
        [PostUitls Post:myzturl parameters:params success:^(id response) {
            UserInfoUpdateResde *resdmode=[UserInfoUpdateResde resdeWithDict:response];
            if ([resdmode.state integerValue]==400) {
                [self.navigationController popViewControllerAnimated:YES];
            }
            hud.labelText=resdmode.msg;
            hud.mode = MBProgressHUDModeText;
            [hud hide:YES afterDelay:1];
        } failure:^(NSError *error) {
            hud.labelText=@"网络错误";
            hud.mode = MBProgressHUDModeText;
        }];

    }
}

-(void)setuptoolbar{
    ZtEidtBar *eidtbar=[[ZtEidtBar alloc]initWithBtnTitleArray:nil WithDelegate:self];
    [self.view addSubview:eidtbar];
}
-(void)share{
    NSArray *titlearray=@[@"微信",@"朋友圈",@"短信"];
    UIImage *weixin=[UIImage imageNamed:@"weixin"];
    UIImage *pengyou=[UIImage imageNamed:@"liulan"];
    UIImage *sms=[UIImage imageNamed:@"duanxin"];
    NSArray *icon=@[weixin,pengyou,sms];
    ShareView *share=[[ShareView alloc]initWithTitle:titlearray andIcons:icon delegate:self];
    [share show];
}
-(void)setupfootview{
    
        ZTFooterView *footer=[ZTFooterView footerWith:self.mode];
        
        self.tableView.tableFooterView=footer;
    
}



-(void)setupaddbtn{
    UIView *bgview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, 76)];
    bgview.backgroundColor=bgGarycolor;
    UIButton *addbtn=[[UIButton alloc]initWithFrame:CGRectMake(16, 24, XHScreenwidth-32, 36)];
    [addbtn setBackgroundImage:[UIImage imageWithStretchableName:@"bo_lbian"] forState:UIControlStateNormal];
    [addbtn setTitle:@"复制展车到我的展厅" forState:UIControlStateNormal];
    
    [addbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addbtn addTarget:self action:@selector(addbtnclick) forControlEvents:UIControlEventTouchUpInside];
   
    [bgview addSubview:addbtn];
    self.tableView.tableFooterView=bgview;
}

-(void)addbtnclick{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText=@"正在复制";
    
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"copy_car";
    params[@"id"]=self.mode.ID;
    
    params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
    params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
    if ([self.user.power integerValue]==8) {
        params[@"pid"]=self.user.parent_id;
    }
    [PostUitls Post:myzturl parameters:params success:^(id response) {
        UserInfoUpdateResde *resdmode=[UserInfoUpdateResde resdeWithDict:response];
        hud.mode = MBProgressHUDModeText;
        if ([resdmode.state integerValue]==400) {
            
        }
        
        hud.labelText=resdmode.msg;
        [hud hide:YES afterDelay:1];
    } failure:^(NSError *error) {
        hud.mode=MBProgressHUDModeText;
        hud.labelText=@"网络错误";
        [hud hide:YES afterDelay:0.5];
    }];

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupNav];
}



-(void)setupNav{
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}
     ];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbg"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTranslucent:YES];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
}

-(void)setupdata{
    [self.dataarray removeAllObjects];
    
    HeaderModel *headermode=[[HeaderModel alloc]init];
    headermode.rowheight=63;
    headermode.name=self.mode.cat_name;
    headermode.time=self.mode.addtime;
    [self.dataarray addObject:headermode];
    NoramlCellMode *cheyuan=[[NoramlCellMode alloc]init];
    cheyuan.title=@"车源类型";
    cheyuan.detail=self.mode.type_name;
    [self.dataarray addObject:cheyuan];
    NoramlCellMode *waiguan=[[NoramlCellMode alloc]init];
    waiguan.title=@"外观颜色";
    waiguan.detail=self.mode.car_outside_color;
    [self.dataarray addObject:waiguan];
    NoramlCellMode *neishi=[[NoramlCellMode alloc]init];
    neishi.title=@"内饰颜色";
    neishi.detail=self.mode.car_inside_color;
    [self.dataarray addObject:neishi];
    PeizhiMode *peizhi=[[PeizhiMode alloc]init];
    peizhi.title=@"配置";
    peizhi.longdetail=self.mode.car_configure;
    if (self.mode.car_configure&&![self.mode.car_configure isEqualToString:@""]) {
        [self.dataarray addObject:peizhi];
    }
    
    PhotoTitleMode *phototitlemode=[[PhotoTitleMode alloc]init];
    [self.dataarray addObject:phototitlemode];
    
    ZTPhotoMode *photomode=[[ZTPhotoMode alloc]init];
   
    if (![self.mode.pic isKindOfClass:[NSString class]]&&self.mode.pic) {
        photomode.imgurls=self.mode.pic;
    }
    if (photomode.imgurls.count>0&&self.mode.pic) {
         [self.dataarray addObject:photomode];
        photomode.rowheight=(200+8)*photomode.imgurls.count+8;
        
    }
    
    NormalTitleMode *ntitlemode=[[NormalTitleMode alloc]init];
    [self.dataarray addObject:ntitlemode];
    NameMode *name=[[NameMode alloc]init];
    
    name.title=self.mode.cat_name;
    [self.dataarray addObject:name];
    
    BlueDetailMode *cheshenjia=[[BlueDetailMode alloc]init];
    cheshenjia.title=@"车身价";
    cheshenjia.detail=[NSString stringWithFormat:@"%@元",self.mode.price_zdj];
    [self.dataarray addObject:cheshenjia];
    
    NoramlCellMode *gouzhisui=[[NoramlCellMode alloc]init];
    gouzhisui.title=@"购置税";
    gouzhisui.detail=[NSString stringWithFormat:@"%@元",self.mode.price_gzs];
    if ([self.mode.price_gzs integerValue]>0) {
         [self.dataarray addObject:gouzhisui];
    }
   
    
    NoramlCellMode *shangpai=[[NoramlCellMode alloc]init];
    shangpai.title=@"上牌费";
    shangpai.detail=[NSString stringWithFormat:@"%@元",self.mode.price_spf];
    if ([self.mode.price_spf integerValue]>0) {
        [self.dataarray addObject:shangpai];
    }
    

   
    
    NoramlCellMode *zonghexian=[[NoramlCellMode alloc]init];
    zonghexian.title=@"综合险";
    zonghexian.detail=[NSString stringWithFormat:@"%@元",self.mode.price_zhx];
    if ([self.mode.price_zhx integerValue]>0) {
        [self.dataarray addObject:zonghexian];
    }

    
    
    NoramlCellMode *qita=[[NoramlCellMode alloc]init];
    qita.title=@"其他费用";
    qita.detail=[NSString stringWithFormat:@"%@元",self.mode.price_other];
    if ([self.mode.price_other integerValue]>0) {
        [self.dataarray addObject:qita];
    }
   
    
    BlueDetailMode *heji=[[BlueDetailMode alloc]init];
    heji.title=@"合计";
    heji.detail=[NSString stringWithFormat:@"%ld万",([self.mode.yhprice integerValue]+[self.mode.allprice integerValue])];
    [self.dataarray addObject:heji];
    
    NoramlCellMode *zhongheyouhui=[[NoramlCellMode alloc]init];

    
    zhongheyouhui.title=@"综合优惠";
    zhongheyouhui.detail=[NSString stringWithFormat:@"%@元",self.mode.yhprice];
    if ([self.mode.yhprice integerValue]>0) {
        [self.dataarray addObject:zhongheyouhui];
    }
    
    
    BlueDetailMode *quanbao=[[BlueDetailMode alloc]init];
    quanbao.title=@"全包";
    quanbao.detail=[NSString stringWithFormat:@"%@元",self.mode.allprice];
     [self.dataarray addObject:quanbao];
    
    NoramlCellMode *beizhu=[[NoramlCellMode alloc]init];
    beizhu.title=@"备注";
    beizhu.detail=![self.mode.remark isEqualToString:@""]?self.mode.remark:@"无";
   
    [self.dataarray addObject:beizhu];
    [self.tableView reloadData];
    if (self.isFromSearch) {
        [self setupaddbtn];
    }
    [self setupfootview];
}
-(NSMutableArray *)dataarray{
    if (_dataarray==nil) {
        _dataarray=[NSMutableArray array];
    }
    return _dataarray;
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
-(UITableView *)tableView{
    if (_tableView==nil) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, XHScreenheight) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=bgGarycolor;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.dataarray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NoramlCellMode *mode=self.dataarray[indexPath.row];
    
    if ([mode isKindOfClass:[HeaderModel class]]) {
        HeaderTableViewCell *cell=[HeaderTableViewCell cellWithTableView:tableView];
        HeaderModel *header=mode;
        cell.timelable.text=[NSDate dateStrFromTimeStr:header.time];
        cell.namelable.text=header.name;
        return cell;
    }else if([mode isKindOfClass:[PhotoTitleMode class]]){
        PhotoTitleTableViewCell *cell=[PhotoTitleTableViewCell cellWithTableView:tableView];
        return cell;
    }else if([mode isKindOfClass:[ZTPhotoMode  class]]){
        ZTPhotoMode *photo=mode;
        ZTPhotoTableViewCell *cell=[ZTPhotoTableViewCell cellWithTablView:tableView];
        cell.imgurls=photo.imgurls;
        return cell;
    }
    else if([mode isKindOfClass:[NormalTitleMode class]]){
        NormallTitleTableViewCell *cell=[NormallTitleTableViewCell cellWithTableView:tableView];
        return cell;
    }else if ([mode isKindOfClass:[PeizhiMode class]]){
        PeizhiMode *pmode=mode;
        PeiZhiTableViewCell *cell=[PeiZhiTableViewCell cell];
        cell.detailtext.text=pmode.longdetail;
        return cell;
    }
    else {
        NoramlTableViewCell *cell=[NoramlTableViewCell cellWithTableView:tableView];
        cell.textLabel.text=mode.title;
        cell.detailTextLabel.text=mode.detail;
        if ([mode isKindOfClass:[NameMode class]]) {
            cell.detailTextLabel.hidden=YES;
        }else{
             cell.detailTextLabel.hidden=NO;
        }
        if ([mode isKindOfClass:[BlueDetailMode class]]) {
             cell.detailTextLabel.textColor=tintblue;
        }else{
            cell.detailTextLabel.textColor=textnormalGary;
        }
        return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NoramlCellMode *mode=self.dataarray[indexPath.row];
    
    return mode.rowheight?mode.rowheight:44;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
